package cn.vcjf.washcar.common.controller;

import cn.vcjf.washcar.common.util.weixin.AbstractWxPayAuth;
import cn.vcjf.washcar.common.util.weixin.WxPayAuthApi;
import cn.vcjf.washcar.common.web.JsonResult;
import cn.vcjf.washcar.common.web.TableResult;
import cn.vcjf.washcar.system.entity.SysUser;
import cn.vcjf.washcar.system.service.SysUserService;
import cn.vcjf.washcar.washcarorder.service.WashCarOrderService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SysUserService userService;
	@Resource
	private WashCarOrderService washCarOrderService;
	@Resource
	private AbstractWxPayAuth abstractWxPayAuth;

	@RequestMapping("/{page}.page")
	public ModelAndView pageUI(@PathVariable String page,String id,ModelAndView mode){
		logger.debug("/pages/"+page);
		//返回的字符串会对应一个/WEB-INF/pages/index.jsp页面
		if(page.equals("user_edit")&&StringUtils.isBlank(id)){
			SysUser user = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
			id=user.getId()+"";
		}
		mode.addObject("id",id);
		mode.setViewName(page);
		return mode;
	}

	@RequestMapping("/mainUI.do")
	public String indexUI(){
		logger.debug("mainUI");
		SysUser user = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
		if(user==null){
			return "loginUI.do";
		}
		//返回的字符串会对应一个/WEB-INF/pages/index.jsp页面
		return "main";
	}
	@RequestMapping("doFindUserMenus.do")
	@ResponseBody
	public JsonResult doFindUserMenus() {
		SysUser user = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
		return new JsonResult(userService.findUserMenus(user.getId()));
	}
	/**
	 * 获取七牛token
	 */
	@RequestMapping("getUpToken.do")
	@ResponseBody
	public TableResult getUpToken(String fileName){
		// 调用方法获取七牛token
		return	new TableResult((Object) userService.getUpToken(fileName));
	}

	/**
	 * 获取管理首页统计数据
	 */
	@RequestMapping("getManagerIndexData.do")
	@ResponseBody
	public TableResult getManagerIndexData(){
		Map<String, Object> managerIndexData = washCarOrderService.getManagerIndexData();
		return	new TableResult(managerIndexData);
	}
	/**
	 * 动态获取管理首页订单统计数据
	 *
	 */
	@RequestMapping("getOrderCountData.do")
	@ResponseBody
	public TableResult getOrderCountData(@RequestParam("begDate")
                                                @DateTimeFormat(pattern = "yyyy-MM-dd")
                                                Date begDate,
                                                @RequestParam("endDate")
                                                @DateTimeFormat(pattern = "yyyy-MM-dd")
                                                Date endDate){
		List<Map<String, Object>> managerIndexOrderData = washCarOrderService.getManagerIndexOrderData(begDate,endDate);
		return	new TableResult(managerIndexOrderData);
	}
	/**
	 * 获取管理首页统计图订单统计数据
	 *
	 */
	@RequestMapping("getChartsOrderCountData.do")
	@ResponseBody
	public TableResult getChartsOrderCountData(){
		List<Map<String, Object>> dayOfMonthOrderCount = washCarOrderService.getDayOfMonthOrderCount();

		List<Map<String, Object>> near7DaysOrderCount = washCarOrderService.getNear7DaysOrderCount();

		Map<String, Object> data = new HashMap<>();
		data.put("dayOfMonthOrderCount",dayOfMonthOrderCount);
		data.put("near7DaysOrderCount",near7DaysOrderCount);

		return	new TableResult(data);
	}

///i18n/strings_zh.properties
//	/**
//	 * 获取properties
//	 */
//	@RequestMapping("/i18n/{fileName}.properties")
//	@ResponseBody
//	public byte[] getProperties(@PathVariable String fileName,HttpServletResponse response) throws IOException, URISyntaxException {
//
//		URL resource = this.getClass().getClassLoader().getResource(fileName + ".properties");
//
//		response.setContentType("appliction/octet-stream");
//		fileName=URLEncoder.encode(fileName,"utf-8");
//		response.setHeader("Content-disposition",
//				"attachment;filename="+fileName);
//		//3.获得指定文件的路径对象(java.nio.Path)
//		Path path=Paths.get(resource.toURI());
//		//4.读取path路径对应的文件,并返回字节数组
//		return Files.readAllBytes(path);
//	}
	@Value("${server.domain.name}")
	private String doMain;

	@RequestMapping("getManagerQrCode.do")
	@ResponseBody
	public void getManagerQrCode(HttpServletRequest request,HttpServletResponse response) throws IOException {

//		SysUser user = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("currentUser");
//		request.setAttribute("userId",user.getId());
		String userId = request.getParameter("userId");
		String qrUrl=doMain+"vc-washcar-manager/updateManagerQrCode.do?userId="+userId;

		String redirectUrl = WxPayAuthApi.getRedirectUrl(qrUrl);
//		Map<String,String> object=new HashMap<>();
//		object.put("url",redirectUrl);
		response.sendRedirect(redirectUrl);
	}

	@RequestMapping("updateManagerQrCode.do")
	@ResponseBody
	public TableResult updateManagerQrCode(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String userId = request.getParameter("userId");
		if (StringUtils.isBlank(userId)) {
			return TableResult.ErrorResult("ERROR not userId!");
		}
		abstractWxPayAuth.doGet(request,response);
		return null;
	}
}
